﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Xml;
using Microsoft.VisualStudio.Tools.Office.Runtime.Security;

namespace TShooter.TfsWord.Setup
{
    [RunInstaller(true)]
    public partial class InclusionListInstaller : Installer
    {
        private const string FILE_URI_SCHEME = @"file:///{0}";
        private const string RSA_KEY_VALUE_XPATH = "/asmv1:assembly/sig:Signature/sig:KeyInfo/sig:KeyValue/sig:RSAKeyValue";
        private const string CONTEXT_PARAMETER_NAME = "vstomanifest";
        private const string ASMV1_NM_PREFIX = "asmv1";
        private const string SIG_NM_PREFIX = "sig";
        private const string ASMV1_NM = "urn:schemas-microsoft-com:asm.v1";
        private const string SIG_NM = "http://www.w3.org/2000/09/xmldsig#";

        public InclusionListInstaller()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            var doc = new XmlDocument();
            var vstoManifest = Context.Parameters[CONTEXT_PARAMETER_NAME];
            
            doc.Load(vstoManifest);
            var mgr = new XmlNamespaceManager(doc.NameTable);
            mgr.AddNamespace(ASMV1_NM_PREFIX, ASMV1_NM);
            mgr.AddNamespace(SIG_NM_PREFIX, SIG_NM);

            var rsa = (XmlElement)doc.SelectSingleNode(RSA_KEY_VALUE_XPATH, mgr);
            var publicKey = rsa.OuterXml;
            var solutionLocation = new Uri(string.Format(FILE_URI_SCHEME, vstoManifest));

            var entry = new AddInSecurityEntry(solutionLocation, publicKey);
            UserInclusionList.Add(entry);
        }

        public override void Uninstall(IDictionary savedState)
        {
            var vstoManifest = Context.Parameters[CONTEXT_PARAMETER_NAME];
            var solutionLocation = new Uri(string.Format(FILE_URI_SCHEME, vstoManifest));
            UserInclusionList.Remove(solutionLocation);
        }
    }
}
